package controller;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;

@SuppressWarnings("serial")
public class ForgotServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		String path = ((HttpServletRequest)request).getRequestURI();
		
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	
        	response.getWriter().println("Bad request : "+request.getRequestURI());
        	response.getWriter().close();
        	return ;
        	
        }

		st.nextToken();
		String name = st.nextToken();
		
		if(name!=null&&!name.equals(""))
		{
			DBCollection collection = Data.data("users");
			DBObject dbObject = collection.findOne(new BasicDBObject("forgot",name));
			if(dbObject!=null)
			{
				int pas = new Random().nextInt(10000);
				try {
					dbObject.put("password", Utils.md5(String.valueOf(pas)));
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
				}
				dbObject.put("forgot", "");
				collection.save(dbObject);
				request.setAttribute("infos", "New Password : "+pas);
			} else {
				request.setAttribute("infos", "The active code is not correct or has been used before. To get the new password, <a href='/forgot-password'>click here</a>");
			}
		} else {
			request.setAttribute("infos", "The active code is not correct or has been used before. To get the new password, <a href='/forgot-password'>click here</a>");
		}
		try {
			request.getRequestDispatcher("/forgot.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
